<template>
  <div style="height: 100vh;width: 1200px;margin: 0 auto;">
    <div style="display: flex;justify-content: space-between;padding: 10px 0px;">
      <router-link to="/main/renshi/kaoqing" style="">返回</router-link>
      <span style="display: grid;grid-template-columns: repeat(4, 1fr);gap: 10px;">
        <span @click="addRecord">新增项</span>
        <span @click="deleteSelectedRecords">批量删除</span>
        <span @click="saveData">保存</span>
        <router-link to="/main/renshi/kaoqing/kqguanli/huizong-list" style="">列表</router-link>
      </span>
    </div>
    <h2>考勤汇总表</h2>
    <p style="margin: 10px 0px;">日期范围：从 <input v-model="dateRange.start" type="date" /> 到 <input v-model="dateRange.end"
        type="date" /></p>
    <div style="width: 1200px;margin: 0 auto;overflow: auto;">
      <table border="1" style="text-align: center;">
        <thead>
          <tr>
            <th rowspan="2"><input type="checkbox" @change="toggleSelectAll" v-model="selectAll"></th>
            <th rowspan="2">序号</th>
            <th rowspan="2">工号</th>
            <th rowspan="2">姓名</th>
            <th rowspan="2">班组名称</th>
            <th colspan="2">迟到</th>
            <th colspan="2">早退</th>
            <th colspan="2">旷工</th>
            <th rowspan="2">年假(H)</th>
            <th rowspan="2">婚假(H)</th>
            <th rowspan="2">产假(H)</th>
            <th rowspan="2">丧假(H)</th>
            <th rowspan="2">病假(H)</th>
            <th rowspan="2">事假(H)</th>
            <th rowspan="2">工伤(H)</th>
            <th rowspan="2">停工待料(H)</th>
            <th rowspan="2">公出(H)</th>
            <th rowspan="2">节假日(H)</th>
            <th rowspan="2">正班(H)</th>
            <th rowspan="2">平时加班(H)</th>
            <th rowspan="2">周末加班(H)</th>
            <th rowspan="2">节假日加班(H)</th>
            <th rowspan="2">总工时(H)</th>
            <th rowspan="2">漏卡次数</th>
            <th rowspan="2">夜班津贴补助次数</th>
            <th rowspan="2">员工确认</th>
          </tr>
          <tr>
            <td>时间</td>
            <td>次数</td>
            <td>时间</td>
            <td>次数</td>
            <td>时间</td>
            <td>次数</td>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in attendanceList" :key="index">
            <td><input type="checkbox" v-model="selectedRecords" :value="index" @change="updateSelectAll" /></td>
            <td>{{ index + 1 }}</td>
            <td><input v-model="item.employeeId" /></td>
            <td><input v-model="item.name" /></td>
            <td><input v-model="item.groupName" /></td>
            <td><input v-model="item.lateTime" /></td>
            <td><input v-model="item.lateCount" type="number" /></td>
            <td><input v-model="item.earlyLeaveTime" /></td>
            <td><input v-model="item.earlyLeaveCount" type="number" /></td>
            <td><input v-model="item.absenteeismTime" /></td>
            <td><input v-model="item.absenteeismCount" type="number" /></td>
            <td><input v-model="item.annualLeave" type="number" /></td>
            <td><input v-model="item.marriageLeave" type="number" /></td>
            <td><input v-model="item.maternityLeave" type="number" /></td>
            <td><input v-model="item.funeralLeave" type="number" /></td>
            <td><input v-model="item.sickLeave" type="number" /></td>
            <td><input v-model="item.personalLeave" type="number" /></td>
            <td><input v-model="item.workInjuryLeave" type="number" /></td>
            <td><input v-model="item.shutdownMaterialTime" type="number" /></td>
            <td><input v-model="item.businessTripTime" type="number" /></td>
            <td><input v-model="item.holidayTime" type="number" /></td>
            <td><input v-model="item.regularShiftTime" type="number" /></td>
            <td><input v-model="item.weekdayOvertimeTime" type="number" /></td>
            <td><input v-model="item.weekendOvertimeTime" type="number" /></td>
            <td><input v-model="item.holidayOvertimeTime" type="number" /></td>
            <td><input v-model="item.totalWorkHours" type="number" /></td>
            <td><input v-model="item.missedCardCount" type="number" /></td>
            <td><input v-model="item.nightShiftAllowanceCount" type="number" /></td>
            <td><input v-model="item.employeeConfirmation" /></td>
          </tr>
        </tbody>
      </table>
    </div>
    <p style="display: flex;justify-content: space-between;"><span>表单编号及版本：AM-JY-054 A/0</span> <span>保存期限：长期</span></p>
  </div>
</template>
<script>
import axios from 'axios';
import { batchSaveAttendanceSummary, getAttendanceSummaryDetail } from '@/api/attendanceSummary';

export default {
  data() {
    return {
      id: null,
      dateRange: {
        start: '',
        end: ''
      },
      attendanceList: [],
      selectedRecords: [],
      selectAll: false
    };
  },
  created() {
    this.attendanceList = [this.getEmptyRecord()];
    // 从路由参数中获取id
    const id = this.$route.query.id;
    if (id) {
      this.id = id;
      this.fetchDetail(id);
    }
  },
  methods: {
    getEmptyRecord() {
      return {
        employeeId: '',
        name: '',
        groupName: '',
        lateTime: '',
        lateCount: 0,
        earlyLeaveTime: '',
        earlyLeaveCount: 0,
        absenteeismTime: '',
        absenteeismCount: 0,
        annualLeave: 0,
        marriageLeave: 0,
        maternityLeave: 0,
        funeralLeave: 0,
        sickLeave: 0,
        personalLeave: 0,
        workInjuryLeave: 0,
        shutdownMaterialTime: 0,
        businessTripTime: 0,
        holidayTime: 0,
        regularShiftTime: 0,
        weekdayOvertimeTime: 0,
        weekendOvertimeTime: 0,
        holidayOvertimeTime: 0,
        totalWorkHours: 0,
        missedCardCount: 0,
        nightShiftAllowanceCount: 0,
        employeeConfirmation: ''
      };
    },
    async fetchDetail(id) {
      try {
        const response = await getAttendanceSummaryDetail(id);
        const detail = response.data;

        // 设置日期范围
        if (detail.startDate) {
          this.dateRange.start = detail.startDate.split(' ')[0];
        }
        if (detail.endDate) {
          this.dateRange.end = detail.endDate.split(' ')[0];
        }

        // 设置考勤数据
        this.attendanceList = [detail];
      } catch (error) {
        this.$message.error('获取详情失败：' + error.message);
      }
    },
    // 全选功能
    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedRecords = this.attendanceList.map((_, index) => index);
      } else {
        this.selectedRecords = [];
      }
    },
    // 更新全选状态
    updateSelectAll() {
      this.selectAll = this.selectedRecords.length === this.attendanceList.length;
    },
    // 批量删除功能
    deleteSelectedRecords() {
      if (confirm('确定要删除选中的记录吗？')) {
        this.selectedRecords.sort((a, b) => b - a).forEach(index => {
          this.attendanceList.splice(index, 1);
        });
        this.selectedRecords = [];
        this.selectAll = false;
      }
    },
    // 新增记录功能
    addRecord() {
      this.attendanceList.push(this.getEmptyRecord());
      this.updateSelectAll();
    },
    // 保存数据功能
    async saveData() {
      try {
        if (this.attendanceList.length === 0) {
          this.$message.error('请至少添加一条记录');
          return;
        }

        // 验证必填字段
        for (const record of this.attendanceList) {
          if (!record.employeeId) throw new Error('请填写工号');
          if (!record.name) throw new Error('请填写姓名');
        }

        const params = {
          dateRange: {
            startDate: this.dateRange.start ? this.dateRange.start + ' 00:00:00' : null,
            endDate: this.dateRange.end ? this.dateRange.end + ' 23:59:59' : null
          },
          attendanceList: this.attendanceList.map(item => ({
            ...item,
            id: this.id, // 添加id字段用于更新
            startDate: this.dateRange.start ? this.dateRange.start + ' 00:00:00' : null,
            endDate: this.dateRange.end ? this.dateRange.end + ' 23:59:59' : null
          }))
        };
        await batchSaveAttendanceSummary(params);
        this.$message.success('保存成功');
        this.$router.push('/main/renshi/kaoqing/kqguanli/huizong-list');
      } catch (error) {
        this.$message.error('保存失败：' + error.message);
      }
    }
  }
};
</script>
<style scoped>
table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  border: 1px solid #000;
  padding: 8px;
  white-space: nowrap;
}

input {
  text-align: center;
  border: none;
}

p {
  line-height: 30px;
}
</style>